package service

import (
	"time"

	"xgame.go_server/comm/async_op"
	"xgame.go_server/dao"
	"xgame.go_server/model"
)

// LoginByPasswordAsync 根据用户名称和密码登录
// userName = 用户名称,
// password = 密码
// clientIpAddr = 客户端 IP 地址
func (this *LoginService) LoginByPasswordAsync(
	userName string, password string, clientIpAddr string) *AsyncBizResult[*LoginResult] {
	if len(userName) <= 0 ||
		len(password) <= 0 {
		return nil
	}

	bizResult := NewAsyncBizResult[*LoginResult]()

	// 获取 bindId
	var bindId = async_op.StrToBindId(userName)

	async_op.Process(bindId, func() {
		// 根据用户名称获取用户模型
		user := dao.GetUserDao().GetUserByName(userName)

		nowTime := time.Now().UnixMilli()

		if nil == user {
			// 新建用户
			user = &model.User{
				UserName:   userName,
				Password:   password,
				CreateTime: nowTime,
			}
		}

		// 更新用户
		user.LastLoginTime = nowTime
		user.LastLoginIp = clientIpAddr

		dao.GetUserDao().SaveOrUpdate(user)
		bizResult.PutReturnedObj(&LoginResult{
			User: user,
		})
	}, nil)

	return bizResult
}
